package com.smartcat.service.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smartcat.bean.LoginUserBean;
import com.smartcat.dao.UserInfoMapper;
import com.smartcat.model.GroupInfo;
import com.smartcat.model.UserInfo;
import com.smartcat.model.UserInfoExample;
import com.smartcat.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService{

	private UserInfoMapper userInfoMapper;
	private SqlSession sqlSessionTemplate;
	
	@Autowired
	public void setUserInfoMapper(UserInfoMapper userInfoMapper){
		this.userInfoMapper=userInfoMapper;
	}
	
	@Autowired
	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	}




	@Override
	public UserInfo getUserInfo(int userId) {
		// TODO Auto-generated method stub
		return this.userInfoMapper.selectByPrimaryKey(userId);
	}
	
	
	@Override
	public LoginUserBean getLoginUserBean(int userId) {
		
		return (LoginUserBean)sqlSessionTemplate.selectOne("getUserBean", userId);
	}


	@Override
	public LoginUserBean checkLogin(String userName) {
		LoginUserBean loginUser=null;
		UserInfoExample example=new UserInfoExample();
		example.or().andEmailAddress1EqualTo(userName);
		List<UserInfo> users=userInfoMapper.selectByExample(example);
		if(users!=null && users.size()>0){
			int userId=users.get(0).getUserId();
			loginUser=(LoginUserBean)sqlSessionTemplate.selectOne("getUserBean", userId);
			loginUser.setGroupInfo((List<GroupInfo>)sqlSessionTemplate.selectList("getGroupinfo",userId));
		}

		return loginUser;
	}


	@Override
	public UserInfo validateUserInfo(String email) {
		UserInfo userInfo;
		UserInfoExample uiExample=new UserInfoExample();
		uiExample.or().andEmailAddress1EqualTo(email);
		
		List<UserInfo> users=this.userInfoMapper.selectByExample(uiExample);
		if(users==null || users.size()==0){
			userInfo=new UserInfo();
			userInfo.setEmailAddress1(email);
			userInfo.setUserName(email);
			userInfo.setPassword("123");//default password
			userInfo.setUserNickName(email);
			this.userInfoMapper.insert(userInfo);
		}else{
			userInfo=users.get(0);
		}

		return userInfo;
	}

	@Override
	public List<UserInfo> getAllUsers() {
		UserInfoExample example=new UserInfoExample();
		example.or().andUserIdGreaterThan(0);
		return this.userInfoMapper.selectByExample(example);
	}

	
	
	
}
